<?php

namespace core;

/**
 * Handles all the stuff around pages
 *
 */
class Page
{
	//Page vars
	private $url;

	private $urlArray = array();

	private $params = array();

	private $pages = array();

	private $pagesNames = array();

	private $page = array();

	private $pagesTree;

	private $vars = array();

	public function __construct()
	{
		$this->url = $_GET['url'];
		$this->urlArray = $this->ParseUrl();
		//$this->pages = $this->GetPages();
		$this->pagesTree = $this->GetPagesTree();
		$this->urlArray = $this->BuildUrlArray();
		$this->pagesNames = $this->GetPagesNames();
		//$this->page = $this->GetCurrentPage();
	}

	public function GetUrl($array = false)
	{
		if ($array)
		{
			return $this->urlArray;
		}
		else
		{
			return $this->url;
		}
	}

	public function GetUrlArray()
	{
		return $this->urlArray;
	}

	public function Start()
	{
		$page = $this->GetCurrentPageName();

		$this->SetVars();

		$sxe = core("File")->LoadXml(_COMPONENTS_DIR."pages/$page.page.xml");
		$xml = core("Html")->CreateElement($sxe);

		$title = $this->GetTitle();

		$content = component($xml);

		$content =
		'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>' . $title . '</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta name="description" content="' . $this->GetMeta("description") . '" />
		<meta name="keywords" content="' . $this->GetMeta("keywords") . '" />
	</head>
	<body>
		' . $content . '
	</body>
</html>';

		return $content;
	}

	private function SetVars()
	{
		core("Registry")->Set("url", $this->url, "page");
		core("Registry")->Set("page_id", $this->page['id'], "page");
		core("Registry")->Set("file_name", $this->page['file_name'], "page");
		core("Registry")->Set("url_name", $this->page['url_name'], "page");
		core("Registry")->Set("items_on_page", $this->page['items_on_page'], "page");

		return true;
	}

	public function GetCurrentPageName()
	{
		return $this->page['file_name'];
	}

	public function PageExists($fileName)
	{
		$exists = false;

		$pages = $this->GetPages();

		foreach ($pages as $item)
		{
			if ($item['file_name'] == $fileName)
			{
				$exists = true;
				break;
			}
		}

		return $exists;
	}

	public function GetPageParams($fileName, $param = false)
	{
		if (!in_array($fileName, $this->pagesNames))
		{
			service("debug")->error("Can't get params for non existent page $fileName");
		}

		$pageId = array_search($fileName, $this->pagesNames);

		$pages = $this->GetPages();

		$params = $pages[$pageId];

		if ($param)
		{
			if (!isset($params[$param]))
			{
				service("debug")->error("Parameter $param doesn't exist for page $fileName");
			}

			return $params[$param];
		}
		else
		{
			return $params;
		}
	}

	private function GetPagesNames()
	{
		$res = array();

		$pages = $this->GetPages();

		foreach ($pages as $key=>$item)
		{
			$res[$key] = $item['file_name'];
		}

		return $res;
	}

	public function GetSubPages($fileName)
	{
		$id = $this->GetPageParams($fileName, "id");

		$subPages = array();

		$pages = $this->GetPages();

		foreach ($pages as $item)
		{
			if ($item['parent'] == $id)
			{
				$subPages[] = $item;
			}
		}

		return $subPages;
	}

	public function GetPageUrl($fileName)
	{

	}

	public function GetTitle($fileName = false)
	{
		if (!$fileName)
		{
			$fileName = core("Registry")->Get("file_name", "page");
		}

		$title = $this->GetPageParams($fileName, "title");

		$title = core("I18n")->Translate($title);

		return $title;
	}

	public function GetMeta($type, $fileName = false)
	{
		if (!$fileName)
		{
			$fileName = core("Registry")->Get("file_name", "page");
		}

		return $this->GetPageParams($fileName, $type);
	}

	public function ParseUrl($url = false)
	{
		if(!$url)
		{
			$url = $_GET['url'];
		}

		$urlArray = array_filter(explode("/", $url));

		if (empty($urlArray))
		{

		}
		else
		{

		}
	}

	private function GetPages()
	{
		if (empty($this->pages))
		{
			service("debug")->TimerStart();

			/*
			$title = service("db")->Select("ru")->From("_languages_content")->Where("id", "=", "_pages_stack.title")->GetSql();
			$description = service("db")->Select("ru")->From("_languages_content")->Where("id", "=", "_pages_stack.description")->GetSql();
			$keywords = service("db")->Select("ru")->From("_languages_content")->Where("id", "=", "_pages_stack.keywords")->GetSql();

			$title = "(" . $title . ")";
			$description = "(" . $description . ")";
			$keywords = "(" . $keywords . ")";
			*/

			$this->pages = service("db")->
			//Select("_pages_stack.*", "_pages.file_name AS file_name", $title . " AS title", $description . " AS description", $keywords . " AS keywords")->
			Select("_pages_stack.*", "_pages.file_name AS file_name")->
			From("_pages_stack")->
			Join("_pages")->
			On("_pages.id", "=", "_pages_stack.file_name")->
			Run();

			$pages = array();

			foreach ($this->pages as $item)
			{
				$pages[$item['id']] = $item;
			}

			$this->pages = $pages;
		}

		return $this->pages;
	}

	private function BuildUrlArray()
	{
		$url = array_filter(explode("/", $this->url));

		$pages = $this->GetPages();

		if (empty($url))
		{
			$this->page = $pages[1];

			return array();
		}

		$fileNames = array();

		/*
		Check the url from the beginning
		Check if current page is valid
		Step back as much as needed
		*/

		$tree = $this->pagesTree;

		$tree = $tree[key($tree)]['childNodes'];

		$resultArray = array();

		foreach ($url as $key=>$item)
		{
			$found = false;

			foreach ($tree as $pageId=>$page)
			{
				if ($page['url_name'] == $item)
				{
					$resultArray[] = $page['file_name'];
					$found = true;
					$lastPage = $page;
				}
			}

			if (!$found || !isset($tree[$pageId]['childNodes']))
			{
				break;
			}
			else
			{
				$tree = $tree[$pageId]['childNodes'];
			}
		}

		if (count($url) == count($resultArray))
		{
			$this->page = $lastPage;
		}
		else
		{
			$this->page = $pages[2];
		}

		return $resultArray;
	}

	private function GetPagesTree()
	{
		$dataset = $this->GetPages();

		$tree = array();
		foreach ($dataset as $id=>&$node)
		{
			if ($node['parent'] === null)
			{
				$this->pages[$node['id']]['url'] = $node['url'] = "";

				if (!isset($node['childNodes']))
				{
					$node['childNodes'] = array();
				}

				$tree[$id] = &$node;
			}
			else
			{
				$this->pages[$node['id']]['url'] = $node['url'] = $dataset[$node['parent']]['url'] . $node['url_name'] . "/";

				if (!isset($node['childNodes']))
				{
					$node['childNodes'] = array();
				}

				if (!isset($dataset[$node['parent']]['childNodes']))
				{
					$dataset[$node['parent']]['childNodes'] = array();
				}

				$dataset[$node['parent']]['childNodes'][$id] = &$node;
			}
		}

		return $tree;
	}
}